<?php

namespace App\Logic;

use Common\Logic\BaseLogic;

class PosterLogic extends BaseLogic
{
    private $tempUri = '/ImgFile/UserPoster/template/poster.png';
    private $userPhotoSize = 100;
    private $fontUri = '/ImgFile/UserPoster/template/msyh.ttf';
    private $fontSize = 22;
    private $userPhotoLoca = array(
        'x' => 38,
        'y' => 96,
    );
    private $qrLoca = array(
        'x' => 370,
        'y' => 463,
    );
    private $fontLoca = array(
        'x' => 160,
        'y' => 153,
    );

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取海报.
     *
     * @param type $userId
     * @param type $userName
     * @param type $userPhoto
     *
     * @return type
     */
    public function get($userId, $userName, $userPhoto)
    {
        if (empty($userId) || empty($userPhoto)) {
            return static::$res->err('参数异常');
        }

        $phosterUri = $this->getPhosterUri($userId);
        $phosterFileName = WEB_PATH.$phosterUri;

        // if (file_exists($phosterFileName)) {
        //     return static::$res->suc("成功", DOMIAN . $phosterUri."?v=".C("JS_CSS_VERSION"));
        // }

        //处理用户头像
        $userImgUrl = $this->getUserPhotoImg($userPhoto);
        if (!$userImgUrl) {
            return static::$res->err('用户头像处理失败');
        }
        $userImg = imagecreatefrompng(WEB_PATH.$userImgUrl);

        //设置头像透明
        $color = imagecolorallocate($userImg, 255, 255, 255);
        imagecolortransparent($userImg, $color);
        // imagefill($userImg, 0, 0, $color);

        //获取二维码图片
        $qrImg = $this->getQrImg($userId);

        //获取海报模版
        $tempUri = $this->tempUri;
        $tempUrl = WEB_PATH.$tempUri;
        $tempImg = imagecreatefromstring(file_get_contents($tempUrl));
        if (!$tempImg) {
            return static::$res->err('海报模版不存在');
        }

        $userPhotoLoca = $this->userPhotoLoca;

        imagecopy($tempImg, $userImg, $userPhotoLoca['x'], $userPhotoLoca['y'], 0, 0, imagesx($userImg), imagesx($userImg));
        imagedestroy($userImg);

        $qrLoca = $this->qrLoca;

        imagecopyresampled($tempImg, $qrImg, $qrLoca['x'], $qrLoca['y'], 0, 0, imagesx($qrImg), imagesy($qrImg), imagesx($qrImg), imagesy($qrImg));
        imagedestroy($qrImg);

        if (!empty($userName)) {
            $fontUri = $this->fontUri;
            $fontUrl = WEB_PATH.$fontUri;
            $fontSize = $this->fontSize;
            $fontLoca = $this->fontLoca;
            $black = imagecolorallocate($tempImg, 0, 0, 0);
            imagefttext($tempImg, $fontSize, 0, $fontLoca['x'], $fontLoca['y'], $black, $fontUrl, $userName);
        }

        if (!imagepng($tempImg, $phosterFileName)) {
            return static::$res->err('海报生成失败');
        }
        imagedestroy($tempImg);

        return static::$res->suc('成功', DOMIAN.$phosterUri.'?v='.date('Ymd').'3');
    }

    /**
     * 获取用户圆形透明头像.
     *
     * @param $userPhoto
     *
     * @return bool|resource
     */
    public function getUserPhotoImg($userPhoto)
    {
        $userUri = substr($userPhoto, 8);
        $userUrl = WEB_PATH.$userUri;

        if (!file_exists($userUrl)) {
            return false;
        }

        $size = $this->userPhotoSize;

        //压缩图像到可用尺寸
        $userImgOri = $this->compressImg($userUrl, $size);
        if (!$userImgOri) {
            return false;
        }

        $userImg = imagecreatetruecolor($size, $size);
        imagesavealpha($userImg, true);
        $bg = imagecolorallocatealpha($userImg, 255, 255, 255, 127);
        imagefill($userImg, 0, 0, $bg);

        $r = $size / 2;
        for ($x = 0; $x < $size; ++$x) {
            for ($y = 0; $y < $size; ++$y) {
                $rgbColor = imagecolorat($userImgOri, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($userImg, $x, $y, $rgbColor);
                }
            }
        }
        imagedestroy($userImgOri);

        //将处理好的头像文件保存到服务器中
        $imageUri = '/ImgFile/UserHeadPhoto/'.date('Ymd').'/'.time().'_'.rand(1111, 9999).'.png';
        $fileName = WEB_PATH.$imageUri;

        $path = dirname($fileName);
        is_dir($path) or mkdir($path, 0777, true);

        if (!imagepng($userImg, $fileName)) {
            return false;
        }
        imagedestroy($userImg);

        return $imageUri;
    }

    /**
     * 压缩图像.
     *
     * @param $url
     * @param $size
     *
     * @return bool|resource
     */
    public function compressImg($url, $size)
    {
        if (!file_exists($url)) {
            return false;
        }
        if (empty($size)) {
            return false;
        }

        $imgOri = imagecreatefromstring(file_get_contents($url));
        $img = imagecreatetruecolor($size, $size);
        imagecopyresampled($img, $imgOri, 0, 0, 0, 0, imagesx($img), imagesy($img), imagesx($imgOri), imagesy($imgOri));
        imagedestroy($imgOri);

        return $img;
    }

    /**
     * 获取二维码图像.
     *
     * @param $userId
     *
     * @return resource
     */
    public function getQrImg($userId)
    {
        $qrUri = '/ImgFile/UserPoster/QrTemp/00_'.$userId.'.png';
        $qrUrl = WEB_PATH.$qrUri;

        $wxLogic = new WxLogic();
        $url = $wxLogic->getQcodeUrl($userId);
        if (empty($url)) {
            $url = 'http://www.tasksys.online'.C('WEB_DOMAIN').'?parentId='.$userId;
        }

        Vendor('PhpQrCode.phpqrcode', dirname(__FILE__).'/../../Common/Vendor');
        \QRcode::png($url, $qrUrl, QR_ECLEVEL_L, 4, 0);

        $qrImg = imagecreatefromstring(file_get_contents($qrUrl));

        return $qrImg;
    }

    /**
     * 获取海报资源地址
     *
     * @param $userId
     *
     * @return string
     */
    public function getPhosterUri($userId)
    {
        return '/ImgFile/UserPoster/'.$userId.'.png';
    }
}
